package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.constants.RedisConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.redis.CacheService;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsService wmNewsService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 自动审核文章
     * @param id
     */
    @Async("taskExecutor")  //标明，当前方法是一个被异步调用的方法
    @Override
//    @GlobalTransactional
    public void autoScanWmNews(Integer id) {

        //1.查询文章  根据id查询
        WmNews wmNews = wmNewsService.getById(id);
        if(null == wmNews){
            throw new RuntimeException("WmNewsAutoScanServiceImpl-自媒体文章不存在");
        }

        //2.当前的文章是待审核状态（1）
        if(wmNews.getStatus().equals(WmNews.Status.SUBMIT.getCode())){
            //提取文章的纯文本和图片（内容的图片和封面图片）
            Map<String,Object> textAndImage = handleTextAndImages(wmNews);

            //审核文章内容中是否包含自管理的敏感词
            boolean isSensitive = handleSensitive((String) textAndImage.get("content"),wmNews);
            if(!isSensitive) return;

            //3.文章文本审核
            boolean isTextScan = handleTextScan((String) textAndImage.get("content"),wmNews);
            if(!isTextScan) return;

            //4.文章图片审核
            boolean isImageScan = handleImageScan((List<String>) textAndImage.get("images"),wmNews);
            if(!isImageScan) return;

            //5.审核成功  调用远程接口 feign接口 保存app端的文章    修改wm_news的状态为9
            ResponseResult responseResult = saveAppArticle(wmNews);
            if(responseResult == null || !responseResult.getCode().equals(200)){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-保存app端的文章失败");
            }

//            int a = 1/0;


            //回填article的id
            wmNews.setArticleId((Long) responseResult.getData());
            updateWmNews(wmNews,WmNews.Status.PUBLISHED.getCode(),"发布成功");

            //发送消息，生成app端详情页面
            //发送消息，通知article端生成文章详情页面
            Map<String,Object> map = new HashMap<>();
            map.put("articleId",wmNews.getArticleId()+"");
            kafkaTemplate.send(WmNewsMessageConstants.ARTICLE_STATIC_URL_CREATE_TOPIC, JSON.toJSONString(map));

        }

    }

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 审核文章内容中是否包含自管理的敏感词
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        //redis是否有数据
        String value = cacheService.get(RedisConstants.SENSITIVE_CACHE_KEY);
        List<String> sensitiveStrList = null;
        if(value == null || value == ""){
            List<WmSensitive> wmSensitiveList = wmSensitiveMapper
                    .selectList(Wrappers.<WmSensitive>lambdaQuery().select(WmSensitive::getSensitives));

            sensitiveStrList = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
            cacheService.set(RedisConstants.SENSITIVE_CACHE_KEY,JSON.toJSONString(sensitiveStrList));
        }else {
            sensitiveStrList = JSON.parseObject(value, List.class);
        }

        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveStrList);

        //匹配文章内容中是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content + "-" + wmNews.getTitle());
        if(map.size() > 0){
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(), "文章中包含了敏感词="+map);
            return false;
        }
        return true;
    }

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 保存app端的文章
     * @param wmNews
     */
    public ResponseResult saveAppArticle(WmNews wmNews) {

        ArticleDto dto = new ArticleDto();
        //属性拷贝
        BeanUtils.copyProperties(wmNews,dto);

        //布局
        dto.setLayout(wmNews.getType());

        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if(wmChannel != null){
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorId(wmUser.getId().longValue());
            dto.setAuthorName(wmUser.getName());
        }

        //文章(ap_article)id
        if(wmNews.getArticleId() != null){
            dto.setId(wmNews.getArticleId());
        }

        //创建时间
        dto.setCreatedTime(new Date());

        //发送请求，远程调用
        return articleClient.saveAppArticle(dto);
    }

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 图片审核
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImageScan(List<String> images, WmNews wmNews) {

        boolean flag = true;

        //校验
        if(images == null || images.size() == 0){
            return flag;
        }

        //去重
        images = images.stream().distinct().collect(Collectors.toList());


        List<byte[]> imageList = new ArrayList<>();

        try {
            //下载图片
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);

                //图片文字识别，审核
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                BufferedImage bufferedImage = ImageIO.read(byteArrayInputStream);
                String result = tess4jClient.doOCR(bufferedImage);
                //识别文字之后，进行自管理的敏感词审核
                boolean isSensitive = handleSensitive(result, wmNews);
                if(!isSensitive){
                    return isSensitive;
                }

                imageList.add(bytes);
            }

            //审核图片

            Map map = greenImageScan.imageScan(imageList);
            if(map != null){
                //审核失败
                if(map.get("suggestion").equals("block")){
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章中包含了敏感内容");
                    flag = false;
                }

                //人工审核
                if(map.get("suggestion").equals("review")){
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章中包含了不确定内容");
                    flag = false;
                }
            }
        } catch (Exception e) {
            flag = false;
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章图片审核失败");
        }

        return flag;
    }

    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 文章文本审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {

        boolean flag = true;

        try {
            Map map = greenTextScan.greeTextScan(content+"-"+wmNews.getTitle());
            if(map != null){
                //审核失败
                if(map.get("suggestion").equals("block")){
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "文章中包含了敏感内容");
                    flag = false;
                }

                //人工审核
                if(map.get("suggestion").equals("review")){
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "文章中包含了不确定内容");
                    flag = false;
                }
            }

        } catch (Exception e) {
            flag = false;
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章文本审核失败");

        }
        return flag;
    }

    /**
     * 修改文章
     * @param wmNews
     * @param status
     * @param reason
     */
    public void updateWmNews(WmNews wmNews, Short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsService.updateById(wmNews);
    }

    /**
     * 提取文章的纯文本和图片（内容的图片和封面图片）
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {


        //1.获取内容中的数据
        StringBuilder stringBuilder = new StringBuilder();

        List<String> images = new ArrayList<>();

        if(StringUtils.isNotBlank(wmNews.getContent())){
            List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                //纯文本
                if(map.get("type").equals("text")){
                    stringBuilder.append(map.get("value"));
                }
                //图片
                if(map.get("type").equals("image")){
                    images.add((String) map.get("value"));
                }
            }
        }

        //2.获取封面图片
        if(StringUtils.isNotBlank(wmNews.getImages())){
            String[] arr = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(arr));
        }

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("content",stringBuilder.toString());
        resultMap.put("images",images);

        return resultMap;


    }
}
